package thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;

/**
 * Java线程使用示例大全
 * 
 * 本类展示了Java中线程的各种用法：
 * 1. 线程创建方式
 * 2. 线程生命周期管理
 * 3. 线程同步机制
 * 4. 线程通信
 * 5. 线程池使用
 * 6. 并发工具类
 * 7. 原子操作
 * 8. 锁机制
 * 9. 线程局部变量
 * 10. 定时任务
 */
public class ThreadExamples {
    
    // 共享资源
    private static int counter = 0;
    private static final AtomicInteger atomicCounter = new AtomicInteger(0);
    private static final ReentrantLock lock = new ReentrantLock();
    private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static final Object monitor = new Object();
    private static final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    
    /**
     * 1. 线程创建方式示例
     */
    public static void demonstrateThreadCreation() {
        System.out.println("===== 1. 线程创建方式 =====");
        
        // 1.1 继承Thread类
        Thread thread1 = new Thread("Thread-继承Thread") {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ": 继承Thread类创建");
            }
        };
        
        // 1.2 实现Runnable接口
        Thread thread2 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + ": 实现Runnable接口创建");
        }, "Thread-Runnable");
        
        // 1.3 使用Callable和Future
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(() -> {
            return "Callable任务执行结果";
        });
        
        try {
            System.out.println("Future结果: " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
        
        // 启动线程
        thread1.start();
        thread2.start();
        
        sleep(1);
    }
    
    /**
     * 2. 线程生命周期管理
     */
    public static void demonstrateThreadLifecycle() {
        System.out.println("===== 2. 线程生命周期 =====");
        
        Thread lifecycleThread = new Thread(() -> {
            try {
                System.out.println("线程开始执行...");
                Thread.sleep(2000);
                System.out.println("线程执行完毕");
            } catch (InterruptedException e) {
                System.out.println("线程被中断");
                Thread.currentThread().interrupt();
            }
        }, "LifecycleThread");
        
        System.out.println("线程状态 - 新建: " + lifecycleThread.getState());
        lifecycleThread.start();
        System.out.println("线程状态 - 运行: " + lifecycleThread.getState());
        
        sleep(1);
        System.out.println("线程状态 - 休眠: " + lifecycleThread.getState());
        
        try {
            lifecycleThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程状态 - 终止: " + lifecycleThread.getState());
    }
    
    /**
     * 3. 线程同步机制
     */
    public static void demonstrateSynchronization() {
        System.out.println("===== 3. 线程同步 =====");
        
        // 3.1 synchronized关键字
        Runnable syncTask = () -> {
            synchronized (ThreadExamples.class) {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + ": " + (++counter));
                    sleep(0.1);
                }
            }
        };
        
        // 3.2 ReentrantLock
        Runnable lockTask = () -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " 获取锁");
                sleep(1);
                System.out.println(Thread.currentThread().getName() + " 释放锁");
            } finally {
                lock.unlock();
            }
        };
        
        Thread syncThread1 = new Thread(syncTask, "SyncThread-1");
        Thread syncThread2 = new Thread(syncTask, "SyncThread-2");
        Thread lockThread1 = new Thread(lockTask, "LockThread-1");
        Thread lockThread2 = new Thread(lockTask, "LockThread-2");
        
        syncThread1.start();
        syncThread2.start();
        lockThread1.start();
        lockThread2.start();
        
        try {
            syncThread1.join();
            syncThread2.join();
            lockThread1.join();
            lockThread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 4. 线程通信
     */
    public static void demonstrateThreadCommunication() {
        System.out.println("===== 4. 线程通信 =====");
        
        class MessageQueue {
            private String message;
            private boolean empty = true;
            
            public synchronized String take() throws InterruptedException {
                while (empty) {
                    wait();
                }
                empty = true;
                notifyAll();
                return message;
            }
            
            public synchronized void put(String message) throws InterruptedException {
                while (!empty) {
                    wait();
                }
                empty = false;
                this.message = message;
                notifyAll();
            }
        }
        
        MessageQueue queue = new MessageQueue();
        
        Thread producer = new Thread(() -> {
            String[] messages = {"消息1", "消息2", "消息3"};
            try {
                for (String msg : messages) {
                    queue.put(msg);
                    System.out.println("生产者发送: " + msg);
                    sleep(1);
                }
                queue.put("完成");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "Producer");
        
        Thread consumer = new Thread(() -> {
            try {
                String msg;
                while (!(msg = queue.take()).equals("完成")) {
                    System.out.println("消费者接收: " + msg);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "Consumer");
        
        producer.start();
        consumer.start();
        
        try {
            producer.join();
            consumer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 5. 线程池使用
     */
    public static void demonstrateThreadPool() {
        System.out.println("===== 5. 线程池 =====");
        
        // 5.1 FixedThreadPool
        ExecutorService fixedPool = Executors.newFixedThreadPool(3);
        System.out.println("使用FixedThreadPool执行10个任务:");
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            fixedPool.execute(() -> {
                System.out.println("任务" + taskId + "由" + Thread.currentThread().getName() + "执行");
                sleep(1);
            });
        }
        fixedPool.shutdown();
        
        // 5.2 CachedThreadPool
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        System.out.println("使用CachedThreadPool执行5个任务:");
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            cachedPool.execute(() -> {
                System.out.println("Cached任务" + taskId + "由" + Thread.currentThread().getName() + "执行");
                sleep(0.5);
            });
        }
        cachedPool.shutdown();
        
        // 5.3 ScheduledThreadPool
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(2);
        System.out.println("使用ScheduledThreadPool:");
        
        scheduledPool.schedule(() -> {
            System.out.println("延迟3秒后执行");
        }, 3, TimeUnit.SECONDS);
        
        scheduledPool.scheduleAtFixedRate(() -> {
            System.out.println("每2秒执行一次");
        }, 1, 2, TimeUnit.SECONDS);
        
        sleep(8);
        scheduledPool.shutdown();
    }
    
    /**
     * 6. 并发工具类
     */
    public static void demonstrateConcurrencyUtilities() {
        System.out.println("===== 6. 并发工具类 =====");
        
        // 6.1 CountDownLatch
        CountDownLatch latch = new CountDownLatch(3);
        System.out.println("CountDownLatch示例:");
        
        for (int i = 0; i < 3; i++) {
            final int workerId = i;
            new Thread(() -> {
                System.out.println("工人" + workerId + "开始工作");
                sleep(1 + Math.random() * 2);
                System.out.println("工人" + workerId + "完成工作");
                latch.countDown();
            }, "Worker-" + i).start();
        }
        
        try {
            latch.await();
            System.out.println("所有工人都完成了工作，主线程继续");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // 6.2 CyclicBarrier
        CyclicBarrier barrier = new CyclicBarrier(3);
        System.out.println("\nCyclicBarrier示例:");
        
        for (int i = 0; i < 3; i++) {
            final int runnerId = i;
            new Thread(() -> {
                try {
                    System.out.println("跑者" + runnerId + "到达起点");
                    barrier.await();
                    System.out.println("跑者" + runnerId + "开始跑步");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "Runner-" + i).start();
        }
        
        sleep(3);
        
        // 6.3 Semaphore
        Semaphore semaphore = new Semaphore(2);
        System.out.println("\nSemaphore示例(2个许可证):");
        
        for (int i = 0; i < 5; i++) {
            final int userId = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("用户" + userId + "获取许可证");
                    sleep(1);
                    System.out.println("用户" + userId + "释放许可证");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "User-" + i).start();
        }
        
        sleep(6);
    }
    
    /**
     * 7. 原子操作
     */
    public static void demonstrateAtomicOperations() {
        System.out.println("===== 7. 原子操作 =====");
        
        AtomicInteger atomicInt = new AtomicInteger(0);
        
        Runnable atomicTask = () -> {
            for (int i = 0; i < 1000; i++) {
                atomicInt.incrementAndGet();
            }
        };
        
        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(atomicTask);
            threads[i].start();
        }
        
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        System.out.println("原子操作结果: " + atomicInt.get());
        
        // 非原子操作对比
        counter = 0;
        Runnable nonAtomicTask = () -> {
            for (int i = 0; i < 1000; i++) {
                counter++;
            }
        };
        
        for (int i = 0; i < 10; i++) {
            new Thread(nonAtomicTask).start();
        }
        
        sleep(2);
        System.out.println("非原子操作结果: " + counter);
    }
    
    /**
     * 8. 读写锁
     */
    public static void demonstrateReadWriteLock() {
        System.out.println("===== 8. 读写锁 =====");
        
        List<String> data = new ArrayList<>();
        
        // 写线程
        Thread writer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                readWriteLock.writeLock().lock();
                try {
                    data.add("数据" + i);
                    System.out.println("写入: 数据" + i);
                    sleep(0.5);
                } finally {
                    readWriteLock.writeLock().unlock();
                }
            }
        }, "Writer");
        
        // 读线程
        Runnable readerTask = () -> {
            for (int i = 0; i < 10; i++) {
                readWriteLock.readLock().lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " 读取: " + data);
                    sleep(0.3);
                } finally {
                    readWriteLock.readLock().unlock();
                }
            }
        };
        
        Thread reader1 = new Thread(readerTask, "Reader-1");
        Thread reader2 = new Thread(readerTask, "Reader-2");
        
        reader1.start();
        reader2.start();
        writer.start();
        
        try {
            reader1.join();
            reader2.join();
            writer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 9. 线程局部变量
     */
    public static void demonstrateThreadLocal() {
        System.out.println("===== 9. 线程局部变量 =====");
        
        Runnable task = () -> {
            int value = threadLocal.get();
            value += new Random().nextInt(100);
            threadLocal.set(value);
            System.out.println(Thread.currentThread().getName() + " 的线程局部变量: " + threadLocal.get());
            threadLocal.remove();
        };
        
        Thread thread1 = new Thread(task, "Thread-1");
        Thread thread2 = new Thread(task, "Thread-2");
        
        thread1.start();
        thread2.start();
        
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 10. 定时任务
     */
    public static void demonstrateScheduledTasks() {
        System.out.println("===== 10. 定时任务 =====");
        
        // 使用ScheduledExecutorService
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        
        Runnable task = () -> {
            System.out.println("定时任务执行于: " + java.time.LocalTime.now());
        };
        
        System.out.println("开始执行定时任务...");
        scheduler.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);
        
        sleep(6);
        scheduler.shutdown();
        
        // 使用Timer
        System.out.println("\n使用Timer执行一次性任务:");
        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                System.out.println("Timer任务执行于: " + java.time.LocalTime.now());
            }
        }, 1000);
        
        sleep(2);
        timer.cancel();
    }
    
    /**
     * 11. 线程中断处理
     */
    public static void demonstrateThreadInterruption() {
        System.out.println("===== 11. 线程中断 =====");
        
        Thread interruptibleThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("工作中...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("收到中断信号，准备退出");
                    Thread.currentThread().interrupt();
                }
            }
            System.out.println("线程已安全退出");
        }, "InterruptibleThread");
        
        interruptibleThread.start();
        
        sleep(3);
        interruptibleThread.interrupt();
        
        try {
            interruptibleThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 12. 守护线程
     */
    public static void demonstrateDaemonThread() {
        System.out.println("===== 12. 守护线程 =====");
        
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("守护线程在后台运行...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DaemonThread");
        
        daemonThread.setDaemon(true);
        daemonThread.start();
        
        sleep(3);
        System.out.println("主线程结束，守护线程将自动退出");
    }
    
    /**
     * 13. 线程优先级
     */
    public static void demonstrateThreadPriority() {
        System.out.println("===== 13. 线程优先级 =====");
        
        Thread lowPriority = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("低优先级线程: " + i);
            }
        }, "LowPriority");
        
        Thread highPriority = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("高优先级线程: " + i);
            }
        }, "HighPriority");
        
        lowPriority.setPriority(Thread.MIN_PRIORITY);
        highPriority.setPriority(Thread.MAX_PRIORITY);
        
        lowPriority.start();
        highPriority.start();
        
        try {
            lowPriority.join();
            highPriority.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 14. CompletableFuture异步编程
     */
    public static void demonstrateCompletableFuture() {
        System.out.println("===== 14. CompletableFuture异步编程 =====");
        
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("异步任务开始");
            sleep(2);
            return "异步任务结果";
        });
        
        future.thenAccept(result -> {
            System.out.println("接收结果: " + result);
        });
        
        future.exceptionally(ex -> {
            System.out.println("异常: " + ex.getMessage());
            return "默认值";
        });
        
        try {
            System.out.println("等待结果: " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    
    private static void sleep(double seconds) {
        try {
            Thread.sleep((long)(seconds * 1000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    public static void main(String[] args) {
        System.out.println("Java线程使用示例大全");
        System.out.println("==================");
        
        demonstrateThreadCreation();
        sleep(1);
        
        demonstrateThreadLifecycle();
        sleep(1);
        
        demonstrateSynchronization();
        sleep(1);
        
        demonstrateThreadCommunication();
        sleep(1);
        
        demonstrateThreadPool();
        sleep(1);
        
        demonstrateConcurrencyUtilities();
        sleep(1);
        
        demonstrateAtomicOperations();
        sleep(1);
        
        demonstrateReadWriteLock();
        sleep(1);
        
        demonstrateThreadLocal();
        sleep(1);
        
        demonstrateScheduledTasks();
        sleep(1);
        
        demonstrateThreadInterruption();
        sleep(1);
        
        demonstrateDaemonThread();
        sleep(1);
        
        demonstrateThreadPriority();
        sleep(1);
        
        demonstrateCompletableFuture();
        
        System.out.println("\n所有示例执行完毕！");
    }
}